<template>
  <div class="view-fill">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <full-screen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button
            :disabled="!canSave"
            v-if="!id && $permission('amortizationDeptAdjust:saveAndSubmit')"
            @click="saveAndSubmit()"
            >保存并提交</el-button
          >
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button @click="addProduct">添加资产</el-button>
              </template>

              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除资产</el-button
                >
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  :api="scanInfo.api"
                  :is-finance-asset="true"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="false"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                      >{{ scope.row.assetName }}</span
                    >
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </full-screen>
    </div>
    <select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="true"
      :tableKey="'addFinanceAssetByUse-com.slip.spd.entity.vo.core.CoreAssetVO'"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
    <AmortizationAdjust
      v-if="amortizationAdjustInfo.visible"
      v-model:show-dialog="amortizationAdjustInfo.visible"
      :left-data="amortizationAdjustInfo.leftData"
      :right-data="amortizationAdjustInfo.rightData"
      @callback="amortizationAdjustCallback"
    />
  </div>
</template>
<script setup name="amortizationDeptAdjustModify">
import FullScreen from '@/components/FullScreen/index'
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import PageFilter from '@/components/PageFilter/index'
import selectAsset from '@/components/SelectAsset/index'
import ScanInputBox from '@/components/SelectAsset/ScanInputBox'
import AmortizationAdjust from '@/views/asset/components/amortizationAdjust'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'
import { getCustomizeSetting } from '@/api/customize'
import { getCurrentFiscalPeriod, assetCardScan } from '@/api/core.js'
import {
  adjustAmortizationDeptDetailCustomizeListAll,
  getAdjustAmortizationDeptById,
  createAdjustAmortizationDept,
  createAdjustAmortizationDeptAndSave,
  updateAdjustAmortizationDept,
} from '@/api/asset.js'
import moment from 'moment'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'id'])
const scanInfo = ref({
  api: assetCardScan,
  query: {
    assetStatus: '1,3',
    assetSourceAuth: true,
    financeAssetFlag: true,
  },
})
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      labelTip: '',
      TimePickerOptions: {},
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    businessDate: [
      {
        required: true,
        message: '请选择业务日期',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'removeProduct',
    },
    {
      type: 'slot',
      value: 'productCodeScan',
    },
  ],
})
const tableInfo = ref({
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '摊销部门调整',
        event: adjustAmortizationDept,
        show: true,
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '6',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isFinanceAsset: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
    },
    queryParams: {},
  },
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const amortizationAdjustInfo = ref({
  visible: false,
  row: {},
  leftData: [],
  rightData: [],
})
const formRefs = ref([])
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
let obj = {
  adjustReason: {
    label: '调整原因',
    value: 'adjustReason',
    componentType: 'input',
    maxlength: 255,
    type: 'input',
    show: false,
    hidden: true,
  },
  adjustAfter: {
    label: '调整后值',
    value: 'adjustAfter',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  adjustBefore: {
    label: '调整前值',
    value: 'adjustBefore',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getFiscalPeriod()

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})
function getFiscalPeriod() {
  getCurrentFiscalPeriod(2).then((res) => {
    if (res && res.success) {
      let index = formInfo.value.fieldList.findIndex(
        (item) => item.value === 'businessDate'
      )
      let fiscalPeriodName = res.data.name
      if (index > -1) {
        formInfo.value.fieldList[
          index
        ].labelTip = `当前会计期间：${fiscalPeriodName}`
        formInfo.value.fieldList[index].TimePickerOptions = {
          disabledDate(time) {
            return (
              time.getTime() <
              new Date(res.data.startDate).getTime() - 24 * 60 * 60 * 1000
            )
          },
        }
      }
    }
  })
}

function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.id
      ? updateAdjustAmortizationDept
      : isSaveAndSubmit === true
      ? createAdjustAmortizationDeptAndSave
      : createAdjustAmortizationDept
    let assetName = tableInfo.value.data
      .filter((item) => !item.adjustAfter)
      .map((item) => item.assetName)
    if (assetName.length) {
      proxy.$alert(`资产【${assetName}】未作任何调整`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    let param = {
      ...formInfo.value.data,
      adjustType: 15,
      details: tableInfo.value.data,
    }
    api(param).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function onCallBackScanData(data, callback) {
  if (data && data.assetCode) {
    data.assetVersion = data.version
    data.assetId = data.id
    data.adjustBefore = data.assetAmortizationDeptVOValue
    if (
      data.assetAmortizationDeptVOList &&
      data.assetAmortizationDeptVOList.length
    ) {
      let arr = proxy.$fn.deepClone(data.assetAmortizationDeptVOList)
      let detailExtList = arr.map((row) => {
        return {
          assetId: data.id,
          relationId: row.amortizationDeptId,
          relationValue: row.amortizationRate,
          relationName: row.amortizationDeptName,
          valueType: 1,
          relationType: 2,
        }
      })
      data['detailExtList'] = detailExtList
    } else {
      data['detailExtList'] = []
    }
    if (tableInfo.value.data) {
      tableInfo.value.data.forEach((item) => {
        item.isChoice = false
      })
      let index = tableInfo.value.data.findIndex(
        (item) => item.assetCode === data.assetCode
      )
      if (index !== -1) {
        callback(true)
      } else {
        tableInfo.value.data.unshift(data)
        callback(false)
      }
    } else {
      tableInfo.value.data.unshift(data)
      callback(true)
    }
  }
}
function adjustAmortizationDept(row) {
  let arr = proxy.$fn.deepClone(row.detailExtList)
  amortizationAdjustInfo.value.leftData = arr.filter(
    (item) => item.valueType === 1
  )
  amortizationAdjustInfo.value.rightData = arr.filter(
    (item) => item.valueType === 2
  )
  amortizationAdjustInfo.value.visible = true
  amortizationAdjustInfo.value.row = row
}
function amortizationAdjustCallback(leftData, data) {
  let row = amortizationAdjustInfo.value.row
  if (data && data.length) {
    let adjustAfter = ''
    data.forEach((item, index) => {
      item.assetId = row.assetId
      // item.relationName = row.relationName
      item.valueType = 2
      item.relationType = 2
      adjustAfter += `${item.relationName}-${item.relationValue}${
        index < data.length - 1 ? ',' : ''
      }`
    })
    let index = tableInfo.value.data.findIndex(
      (item) => item.assetId === row.assetId
    )
    if (index > -1) {
      tableInfo.value.data[index].detailExtList = data.concat(leftData)
      tableInfo.value.data[index]['adjustAfter'] = adjustAfter
    }
  }
}
function addProduct() {
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.id.value = ''
  }
  selectAssetInfo.value.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.assetVersion = item.version
    item.assetId = item.id
    item.adjustBefore = item.assetAmortizationDeptVOValue
    if (
      item.assetAmortizationDeptVOList &&
      item.assetAmortizationDeptVOList.length
    ) {
      let arr = proxy.$fn.deepClone(item.assetAmortizationDeptVOList)
      let detailExtList = arr.map((row) => {
        return {
          assetId: item.id,
          relationId: row.amortizationDeptId,
          relationValue: row.amortizationRate,
          relationName: row.amortizationDeptName,
          valueType: 1,
          relationType: 2,
        }
      })
      item['detailExtList'] = detailExtList
    } else {
      item['detailExtList'] = []
    }
  })
  tableInfo.value.data = data.concat(tableInfo.value.data)
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function getMain() {
  getAdjustAmortizationDeptById(props.id).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
    }
  })
}
function getList() {
  adjustAmortizationDeptDetailCustomizeListAll(filterInfo.value.query).then(
    (res) => {
      if (res && res.success) {
        tableInfo.value.data = res.data
      }
    }
  )
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetAssetManageAmortizationDeptAdjustModify-com.slip.spd.entity.vo.asset.AssetAdjustOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      if (props.id) {
        getMain()
        getList()
      }
    }
  })
}
</script>
